package net;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class BackClient extends Thread {
    final static int port = 8888;
    final static String ServerIp = "localhost";
    static Socket tcpConnection;
    static InputStream inputStream;
    static OutputStream outputStream;

    static {
        try {
            tcpConnection = new Socket(ServerIp, port);
            inputStream = tcpConnection.getInputStream();
            outputStream = tcpConnection.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    final int num = 521;
    byte[] sentence = new byte[num];

    public void SendMassage(String message) {
        try {
            if (message.equals("close")) {
                outputStream.write(message.getBytes());
                inputStream.close();
                outputStream.close();
                tcpConnection.close();
            } else {
                outputStream.write(message.getBytes());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public String receiveMassage() {
        try {
            int count = inputStream.read(sentence);
            String receiveMessage = new String(sentence, 0, count);
            System.out.println(receiveMessage);
            return receiveMessage;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;

    }

    public String receiveFriendMassage() {
        try {
            int count = inputStream.read(sentence);
            return new String(sentence, 0, count);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
